package com.genewoo.codereview.editor.window;

import com.genewoo.codereview.editor.action.ShowCommentsAction;
import com.genewoo.codereview.xmldomain.Comment;
import com.genewoo.codereview.xmldomain.Comments;
import com.genewoo.codereview.xmldomain.CommentsListModel;
import java.io.Serializable;
import java.util.Properties;
import org.openide.ErrorManager;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
public final class ReviewCommentEditorTopComponent extends TopComponent {
    
    private static ReviewCommentEditorTopComponent instance;
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
    
    private static final String PREFERRED_ID = "ReviewCommentEditorTopComponent";
    
    private ReviewCommentEditorTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(ReviewCommentEditorTopComponent.class, "CTL_ReviewCommentEditorTopComponent"));
        setToolTipText(NbBundle.getMessage(ReviewCommentEditorTopComponent.class, "HINT_ReviewCommentEditorTopComponent"));
//        setIcon(Utilities.loadImage(ICON_PATH, true));
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jToolBar = new javax.swing.JToolBar();
        jButtonNew = new javax.swing.JButton();
        jButtonSave = new javax.swing.JButton();
        jButtonDel = new javax.swing.JButton();
        jSplitPaneAll = new javax.swing.JSplitPane();
        jPanelList = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jListCommentList = new javax.swing.JList();
        jPanelText = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextAreaComment = new javax.swing.JTextArea();

        jToolBar.setFloatable(false);
        org.openide.awt.Mnemonics.setLocalizedText(jButtonNew, "New");
        jButtonNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNewActionPerformed(evt);
            }
        });

        jToolBar.add(jButtonNew);

        org.openide.awt.Mnemonics.setLocalizedText(jButtonSave, "Save");
        jButtonSave.setEnabled(false);
        jButtonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSaveActionPerformed(evt);
            }
        });

        jToolBar.add(jButtonSave);

        org.openide.awt.Mnemonics.setLocalizedText(jButtonDel, "Remove");
        jButtonDel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDelActionPerformed(evt);
            }
        });

        jToolBar.add(jButtonDel);

        jSplitPaneAll.setDividerLocation(100);
        jSplitPaneAll.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jListCommentList.setModel(comments);
        jListCommentList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jListCommentList.setMinimumSize(new java.awt.Dimension(0, 200));
        jListCommentList.setPreferredSize(new java.awt.Dimension(0, 100));
        jListCommentList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jListCommentListValueChanged(evt);
            }
        });

        jScrollPane1.setViewportView(jListCommentList);

        org.jdesktop.layout.GroupLayout jPanelListLayout = new org.jdesktop.layout.GroupLayout(jPanelList);
        jPanelList.setLayout(jPanelListLayout);
        jPanelListLayout.setHorizontalGroup(
            jPanelListLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE)
        );
        jPanelListLayout.setVerticalGroup(
            jPanelListLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 99, Short.MAX_VALUE)
        );
        jSplitPaneAll.setTopComponent(jPanelList);

        jTextAreaComment.setColumns(20);
        jTextAreaComment.setEditable(false);
        jTextAreaComment.setLineWrap(true);
        jTextAreaComment.setRows(5);
        jTextAreaComment.setWrapStyleWord(true);
        jTextAreaComment.setDoubleBuffered(true);
        jTextAreaComment.setMaximumSize(new java.awt.Dimension(2147483647, 50));
        jTextAreaComment.setPreferredSize(new java.awt.Dimension(220, 50));
        jScrollPane2.setViewportView(jTextAreaComment);

        org.jdesktop.layout.GroupLayout jPanelTextLayout = new org.jdesktop.layout.GroupLayout(jPanelText);
        jPanelText.setLayout(jPanelTextLayout);
        jPanelTextLayout.setHorizontalGroup(
            jPanelTextLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE)
        );
        jPanelTextLayout.setVerticalGroup(
            jPanelTextLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE)
        );
        jSplitPaneAll.setRightComponent(jPanelText);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jToolBar, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 444, Short.MAX_VALUE)
            .add(jSplitPaneAll, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 444, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jToolBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 25, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jSplitPaneAll, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 386, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents
    
    private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveActionPerformed
        jButtonDel.setEnabled(true);
        jButtonNew.setEnabled(true);
        jTextAreaComment.setEditable(false);
        jButtonSave.setEnabled(false);
        
        if(!jTextAreaComment.getText().trim().equals("")) {
            synchronized(comments) {
                index = 0;
                Comment comment = new Comment();
                comment.setOwner(getUserName());
                comment.setContent(jTextAreaComment.getText());
                comments.add(comment);
                jListCommentList.setSelectedIndex(comments.getSize()-1);
                index = -1;
            }
        }
    }//GEN-LAST:event_jButtonSaveActionPerformed
    
    private void jListCommentListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListCommentListValueChanged
        if (index == -1)
            jTextAreaComment.setText(comments.getElementAt(jListCommentList.getSelectedIndex()).toString());
    }//GEN-LAST:event_jListCommentListValueChanged
    
    private void jButtonDelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDelActionPerformed
        if (jListCommentList.getSelectedIndex() != -1 ) {
            
            synchronized(comments) {
                index = jListCommentList.getSelectedIndex();
                
                //  System.out.println(index);
                
                //        jListCommentList.setModel(new DefaultListModel());
                comments.remove(index);
                jListCommentList.setModel(comments);
                jListCommentList.setSelectedIndex(comments.getSize()-1);
                index = -1;
            }
        }
    }//GEN-LAST:event_jButtonDelActionPerformed
    
    private void jButtonNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNewActionPerformed
        jButtonDel.setEnabled(false);
        jButtonNew.setEnabled(false);
        jTextAreaComment.setText("");
        jTextAreaComment.setEditable(true);
        jButtonSave.setEnabled(true);
    }//GEN-LAST:event_jButtonNewActionPerformed
    
    //
    private CommentsListModel comments = new CommentsListModel(new Comments());
    private int index = 0;
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonDel;
    private javax.swing.JButton jButtonNew;
    private javax.swing.JButton jButtonSave;
    private javax.swing.JList jListCommentList;
    private javax.swing.JPanel jPanelList;
    private javax.swing.JPanel jPanelText;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPaneAll;
    private javax.swing.JTextArea jTextAreaComment;
    private javax.swing.JToolBar jToolBar;
    // End of variables declaration//GEN-END:variables
    
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link findInstance}.
     */
    public static synchronized ReviewCommentEditorTopComponent getDefault() {
        if (instance == null) {
            instance = new ReviewCommentEditorTopComponent();
        }
        return instance;
    }
    
    /**
     * Obtain the ReviewCommentEditorTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized ReviewCommentEditorTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            ErrorManager.getDefault().log(ErrorManager.WARNING, "Cannot find ReviewCommentEditor component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof ReviewCommentEditorTopComponent) {
            return (ReviewCommentEditorTopComponent)win;
        }
        ErrorManager.getDefault().log(ErrorManager.WARNING, "There seem to be multiple components with the '" + PREFERRED_ID + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }
    
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }
    
    private static String getUserName() {
        Properties p = System.getProperties();
        return (String) p.get("user.name");
    }
    
    
    private ShowCommentsAction action;
    
    public void setReviewCommentAction(ShowCommentsAction action) {
        this.action = action;
    }
    
    public void componentOpened() {
        // TODO add custom code on component opening
    }
    
    public void componentClosed() {
        if(null != this.action)
            this.action.closeAll(false);
    }
    
    /** replaces this in object stream */
    public Object writeReplace() {
        return new ResolvableHelper();
    }
    
    protected String preferredID() {
        return PREFERRED_ID;
    }
    
    final static class ResolvableHelper implements Serializable {
        private static final long serialVersionUID = 1L;
        public Object readResolve() {
            return ReviewCommentEditorTopComponent.getDefault();
        }
    }
    
    public void setComments(Comments comments) {
        this.comments.setComments(comments);
    }    
}
